package com.java复习.jdbc.游戏.demo3;

import java.sql.*;

/**
 * 封装类
 */
public class BaseDao {

    //url
    public final static  String URL = "jdbc:mysql://localhost:3306/demo3?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC";
    //驱动
    public final  static String DRIVER = "com.mysql.cj.jdbc.Driver";
    //账号
    public final  static String USER  = "root";
    //密码
    public final  static String PASSWORD  = "ljh990124";

    /**
     * 封装驱动
     * 程序启动时执行一次
     */
    static{
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 封装连接对象
     */
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(URL,USER,PASSWORD);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    /**
     * 封装关闭连接
     */
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(preparedStatement!=null){
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 封装所有的增删改
     * @param sql 自己传sql
     * @param obj 占位符的数据
     * @return
     */
    public static int update(String sql,Object[] obj){
        int num =0;//影响行数
        Connection connection =  getConnection();//获取连接
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);//预编译
            //给占位符赋值
            if(obj!=null&&obj.length>0){//是否有占位符,占位符的个数对应数组的长度
                for(int a=0;a<obj.length;a++){
                    preparedStatement.setObject(a+1,obj[a]);
                }
            }
            //执行sql
           num =  preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //关闭连接
            close(connection,preparedStatement,null);
        }
        return num;
    }

}
